import { DataSourceInstanceSettings, CoreApp, ScopedVars, DataQueryResponse, DataQueryRequest } from '@grafana/data';
import { DataSourceWithBackend, getTemplateSrv } from '@grafana/runtime';

import {MyQuery, MyDataSourceOptions, DEFAULT_QUERY, QueryChannel} from './types';
import {Observable} from "rxjs";

export class DataSource extends DataSourceWithBackend<MyQuery, MyDataSourceOptions> {
  channel: QueryChannel;

  constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
    super(instanceSettings);

    this.channel = instanceSettings.jsonData.channel || QueryChannel.Direct;
  }

  getDefaultQuery(_: CoreApp): Partial<MyQuery> {
    return DEFAULT_QUERY;
  }

  query(request: DataQueryRequest<MyQuery>): Observable<DataQueryResponse> {
    const filteredRequest = {
      ...request,
      targets: request.targets.filter((t) => t.hide !== true),
    };
    return super.query(filteredRequest);
  }

  applyTemplateVariables(query: MyQuery, scopedVars: ScopedVars) {
    return {
      ...query,
      queryText: getTemplateSrv().replace(query.queryText, scopedVars),
    };
  }

  // TODO important !!!
  filterQuery(query: MyQuery): boolean {
    // if no query has been provided, prevent the query from being executed
    return !!query.query || !!query.obsQueryType;
  }
}
